﻿using EasyXaf.EntityDesigner.BusinessObjects;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.EntityProperties;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.ValidationRules;

namespace EasyXaf.EntityDesigner.Commands.PropertyTypeBuilders;

public abstract class NumericalTypeBuilder : IPropertyTypeBuilder
{
    protected abstract PropertyType PropertyType { get; }

    public abstract string[] TypeAliasNames { get; }

    public void Build(EntityProperty property, string typeName, string[] typeParams)
    {
        property.PropertyType = PropertyType;

        if (typeParams.Length == 1)
        {
            if (double.TryParse(typeParams[0], out _))
            {
                property.Entity.ValidationRules.Add(new RangeRule(property.Session)
                {
                    MaxValue = typeParams[0],
                    TargetProperty = property,
                });
            }
        }
        else if (typeParams.Length > 1)
        {
            if (double.TryParse(typeParams[0], out _))
            {
                if (double.TryParse(typeParams[1], out _))
                {
                    property.Entity.ValidationRules.Add(new RangeRule(property.Session)
                    {
                        MinValue = typeParams[0],
                        MaxValue = typeParams[1],
                        TargetProperty = property,
                    });
                }
            }
            if (typeParams.Length > 2 && double.TryParse(typeParams[2], out _))
            {
                property.DefaultValue = typeParams[2];
                property.ColumnDefaultValue = typeParams[2];
            }
        }

        if (typeName.EndsWith('?'))
        {
            property.IsNullable = DefaultBoolean.True;
        }
    }
}
